<template>
  <div ref="progressbarRef" class="progressbar">
    <div class="num" :style="`left:${positionVal-5}px`">
      <countTo :start-val="0" :end-val="value" :duration="400" />%
    </div>
    <div class="bar">
      <div class="inner" :style="`background: ${color}; width:${value}%`" />
    </div>
    <div ref="triangle" class="triangle" :style="`left:${positionVal}px`" />
  </div>
</template>
<script>
import countTo from 'vue-count-to'
export default {
  components: {
    countTo
  },
  props: {
    value: {
      // 进度条value
      type: Number,
      required: true,
      default: 10
    },
    color: {
      type: String,
      default: 'linear-gradient(90deg,#24cbff 30%,#9000ff);'
    }
  },
  data() {
    return {
      parentWidth: 0, // 父布局的宽度
      triangleWidth: 0 // 三角的宽度
    }
  },
  computed: {
    // 三角要定位的位置
    positionVal() {
      return (this.parentWidth * this.value) / 100 - this.triangleWidth / 2
    }
  },
  mounted() {
    this.parentWidth = this.$refs.progressbarRef.offsetWidth
    this.triangleWidth = this.$refs.triangle.offsetWidth
    // 监听窗口大小变化
    window.onresize = (res) => {
      this.parentWidth = this.$refs.progressbarRef.offsetWidth
      this.triangleWidth = this.$refs.triangle.offsetWidth
    }
  }
}
</script>
<style lang="scss" scoped>
.progressbar {
  width: 100%;
  position: relative;
  .num {
    font-size: 20px;
    font-weight: 700;
    color: #fff;
    position: absolute;
    left: 0;
    top: -24px;
    transition: all 0.4s ease;
    white-space: nowrap;

  }
  .bar {
    width: 100%;
    height: 10px;
    border-radius: 5px;
    background-color: #283052;
    .inner {
      height: 100%;
      width: 0;
      border-radius: 5px;
      transition: all 0.4s ease;
    }
  }
  .triangle {
    width: 0;
    height: 0;
    border: 10px solid #fff;
    border-top: 0 solid transparent;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    position: absolute;
    left: 0;
    bottom: -12px;
    transition: all 0.4s ease;
  }
}
</style>
